//
//  Utility.m
//  AOC
//
//  Created by Ha Cong Thuan on 2/8/14.
//  Copyright (c) 2014 Ha Cong Thuan. All rights reserved.
//

#import "Utility.h"
@implementation Utility
+(UILabel *) setFontTitleNavigationitem :(NSString *)titles{
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(40.0f,0.0f,120,40)];
    title.backgroundColor = [UIColor clearColor];
    title.font=[UIFont fontWithName:@"Helvetica" size:17];
    title.textColor=[UIColor blackColor];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = titles;
    return  title;
}
+(UIButton *)setBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [backButton setImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setShowsTouchWhenHighlighted:TRUE];
    return backButton;
}
+(void) saveUserDefaul:(id)value key:(NSString*) key
{
    NSUserDefaults *nd = [NSUserDefaults standardUserDefaults];
    if (value==nil) {
        [nd removeObjectForKey:key];
    }else{
        [nd setObject:value forKey:key];
    }
    [nd synchronize];
}


+(NSString*) formaTimeToLocal:(NSString*)time
{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *yourDate = [dateFormatter dateFromString:time];
    dateFormatter.dateFormat = @"hh:mm:ss";
    NSString *nameReturn = [dateFormatter stringFromDate:yourDate];
    return nameReturn;
}

+(NSString*) ConvertDateToString:(NSDate*)date
{
    if(date==nil)return @"";
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    return[dateFormatter stringFromDate:date];
}

+(NSDate *) convertStringToDateTime:(NSString*)DateString
{
    if([DateString isKindOfClass:[NSDate class]]) return (NSDate *)DateString;
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    //    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";
    NSDate *yourDate = [dateFormatter dateFromString:DateString];
    if(yourDate==nil){
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        yourDate = [dateFormatter dateFromString:DateString];
        if(yourDate==Nil){
            dateFormatter.dateFormat = @"MMMM dd,yyyy";
            yourDate=[dateFormatter dateFromString:DateString];
        }
    }
    return yourDate;
}

+(id) getUserDefault:(NSString*) key
{
    NSUserDefaults *nd = [NSUserDefaults standardUserDefaults];
    return [nd objectForKey:key];
}

+ (NSString*)getDbPath{
    
    NSString *dbPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    return [dbPath stringByAppendingPathComponent:@"Data/mydatabase.sqlite"];
}
+ (void)setDidCopyDb{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:YES forKey:@"SETTINGS_DB_NEED_COPY_STATUS"];
    
    [defaults synchronize];
}

+ (BOOL)isDbCopied{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults boolForKey:@"SETTINGS_DB_NEED_COPY_STATUS"];
}

+ (void)copyDbToPath{
    if ([self isDbCopied]) {
        return;
    }
    //Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // get shared file manager object
    NSString *dbPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    BOOL isDir = NO;
    NSError *error = nil;
    // create path at: APP-ID/Library/DB
    dbPath = [dbPath stringByAppendingPathComponent:@"Data"];
    if (![fileManager fileExistsAtPath:dbPath isDirectory:&isDir] && isDir == NO) {
        if(![fileManager createDirectoryAtPath:dbPath withIntermediateDirectories:YES attributes:nil error:&error]){
            NSLog(@"Failed to create eJournalDataDirectory. Error: %@", error);
            return;
        }
    }
    dbPath = [dbPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
    // check if sql-file existing
	if(![fileManager fileExistsAtPath:dbPath]) {
		// no db existing, do copy new db
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydatabase.sqlite"];
		
		if (![fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error]) {
            // cannot copy new db to location
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        }
	}
    
    // save settings that tell application don't copy new db
    [self setDidCopyDb];
}

+ (void)saveImage: (UIImage*)image ImageName:(NSString*)imageName{
    if (image != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          imageName ];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
//        Contact *model=[Utility getUserGlobal];
//        model.Url=path;
//        [Utility setUserGlobal:model];
//        [Utility saveUserDefaul:path key:PROFILE_IMAGE];
    }
}

- (UIImage*)loadImage:(NSString*)imageName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      imageName];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}
+ (UIImage *)normalizedImage:(UIImage *)image {
    if (image.imageOrientation == UIImageOrientationUp) return image;
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 1.0);
    [image drawInRect:(CGRect){0, 0, image.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

+(UIImage*)loadImage:(NSString*)imageName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      imageName];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}
@end
